#!/bin/bash

# This connection can happen before or after security-secretstore-setup
# (a oneshot service that configures Vault) has already run. The first
# case happens when the content interface is auto-connected and the
# external snap is installed before the edgexfoundry
# snap. In this case there's no action required as security-secretstore-
# -setup will write it's token to the source dir which has been bind
# mounted over the dir of the same name in this snap.
#
# The latter happens when the order is swapped *and* the connection
# is manually connected. In this case since security-secretstore-setup
# (which runs file-token-provider) has already run, the token for
# the external snap will have already been generated, and thus be hidden
# when the content interface directory from the external snap
# is bind mounted on top of the existing /secrets directory.
#
# Since this hook is called before the bind mount has happened, it checks
# to see if the file exists, and if so, copies it to  /tmp.
#
# This script also supports the case where the other snap has multiple
# tokens, i.e. app-service-configurable
#
# NOTE - one final comment, app-service-configurable is included in the
# edgexfoundry snap to provide for Kuiper integration. It's disabled by
# default, and is hard-coded to use the 'rules-engine' profile. Due to
# the way vault tokens work, both the internal app-service-configurable
# instance, and the instance in the app-service-configurable snap are
# able to share the same token.

SLOTDIRS=$(snapctl get :edgex-secretstore-token --slot source.write)
logger "edgex-secretstore-token: prepare SLOTDIRS=$SLOTDIRS"
DIRS=$(jq -r '.[]'  <<< "$SLOTDIRS" ) 

for tokenpath in $DIRS;
do
    filename=$(basename $tokenpath)
    logger "edgex-secretstore-token: prepare $filename"
    APP_SVC_TOKEN="$SNAP_DATA/secrets/${filename}/secrets-token.json"
    TARGET_PATH="/tmp/${filename}-secrets-token.json"
    if [ -f "$APP_SVC_TOKEN" ]; then
        logger "edgex-secretstore-token: token found in $APP_SVC_TOKEN; moving to $TARGET_PATH"
        mv "$APP_SVC_TOKEN" "$TARGET_PATH"
    fi
done



